const express = require('express');
const router = express.Router();
const { query } = require('../utils/db');

// 模拟商品数据
const mockGoodsData = {
  // 商品列表数据
  goodsList: [
    // 1. 二手商品（数码-手机）
    {
      id: '1001',
      type: '自由交易',
      category: { first: '数码产品', second: '手机', id: 101 },
      title: 'iPhone X 苹果手机 全网通',
      subtitle: '64G 深空黑色 99新',
      description: 'Apple iPhone X 苹果手机，64G 深空黑色 99新，全网通，支持5G。',
      price: {
        current: 2999,
        original: 3699,
        drop: 700,
        cheaperThanSimilar: 300
      },
      status: "onSale",
      image: '/static/images/home/goods/1.png',
      location: {
        city: '北京市',
        district: '朝阳区',
        street: '望京街道',
        address: '北京市朝阳区望京SOHO',
        distance: '2.5km'
      },
      liked: true,
      popularity: {
        views: 15678,
        favorites: 234,
        likes: 567,
        shares: 89,
        favoriteRate: '15%',
        goodRate: '99%',
        trend: 'up'
      },
      images: [
        { url: '/static/images/home/goods/1.png', type: 'main' },
        { url: '/static/images/home/goods/2.png', type: 'detail' },
        { url: '/static/images/home/goods/3.png', type: 'detail' },
        { url: '/static/images/home/goods/4.png', type: 'defect' }
      ],
      attributes: [
        { key: '成色', value: '99新' },
        { key: '颜色', value: '深空黑色' },
        { key: '存储', value: '64G' },
        { key: '版本', value: '国行三网通' },
        { key: '重量', value: '0.17kg' },
        { key: '尺寸', value: '143.6×70.9×7.7mm' },
        { key: '电池健康', value: '85%' },
        { key: '购买日期', value: '2022-03-15' },
        { key: '保修截止', value: '2023-03-15' },
        { key: '维修记录', value: '无拆修' },
        { key: '验机报告', value: '已验机' },
        { key: '配件清单', value: '原装充电器、数据线、包装盒' },
        { key: '卖家描述', value: '自用手机，保养很好，无任何问题，因换新机出售。' }
      ],
      services: ['7天无理由', '180天质保', '顺丰包邮', '半年电池换新'],
      promotions: [
        { type: '赠品', title: '品胜充电器套装', value: '价值￥99' },
        { type: '分期', title: '花呗分期', detail: '￥318元/月' }
      ],
      seller: {
        id: 'seller101',
        name: '苹果官方旗舰店',
        avatar: '/static/images/avatar/1.jpg',
        description: '苹果官方旗舰店，专注苹果产品，提供最新、最全的苹果产品信息，服务客户10年以上。',
        tag: '官方认证',
        rating: 4.9,
        followed: true,
        auth: { realName: true, phone: true },
        status: 'online',
        stats: { goodsCount: 156, transactionCount: 2345, replyRate: '98%' },
        recommendedGoods: [
          { id: '1001', title: 'iPhone X 苹果手机 全网通', price: 2999, image: '/static/images/home/goods/1.png' },
          { id: '1002', title: 'Canon EOS M50 Mark II微单相机', price: 1999, image: '/static/images/home/goods/2.png' }
        ]
      },
      comments: { total: 1234, goodRate: '99%', tags: ['成色新', '电池耐用', '服务好'] }
    },
    
    // 3. 新提交的商品（根据提交返回的数据结构）
    {
      id: 'new_1763043230284',
      type: '自由交易',
      category: { first: '数码产品', second: '其他数码', id: 2 },
      title: '二手商品',
      subtitle: '9成新 2021-09-10购买',
      description: '56436543654365',
      price: {
        current: 56,
        original: 555,
        drop: 500,
        cheaperThanSimilar: 0
      },
      status: 'onSale',
      image: '/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png',
      tradeType: '上门自提',
      tradeDetails: '4325436565436543654365365765765',
      location: {
        city: '北京市',
        district: '海淀区',
        street: '中关村街道',
        address: '北京市海淀区中关村',
        distance: '3.8km'
      },
      liked: false,
      popularity: {
        views: 123,
        favorites: 5,
        likes: 8,
        shares: 2,
        favoriteRate: '4%',
        goodRate: '100%',
        trend: 'up'
      },
      images: [
        { url: '/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png', type: 'main' }
      ],
      attributes: [
        { key: '商品状态', value: '9成新' },
        { key: '购买时间', value: '2021-09-10' },
        { key: '保修情况', value: '不保修' },
        { key: '配件情况', value: '654365' }
      ],
      services: ['正品保障', '7天无理由退货'],
      seller: {
        id: 'seller103',
        name: '普通卖家',
        avatar: '/static/images/avatar/default.jpg',
        tag: '个人卖家',
        rating: 4.7,
        status: 'offline',
        stats: { goodsCount: 12, transactionCount: 45, replyRate: '95%' }
      },
      comments: { total: 0, goodRate: '0%', tags: [] }
    },

    // 2. 寄卖商品（数码-无人机）
    {
      id: '1002',
      type: '平台托管',
      category: { first: '数码产品', second: '无人机', id: 105 },
      title: '大疆DJI Mini 3 Pro 无人机 专业航拍器',
      subtitle: '4K/60fps视频 三向避障 34分钟续航',
      description: '大疆DJI Mini 3 Pro 无人机，支持4K/60fps视频，三向避障，34分钟续航。',
      price: { current: 5699, original: 6499, drop: 800, cheaperThanSimilar: 200 },
      status: "onSale",
      image: '/static/images/home/goods/drone1.png',
      location: {
        city: '南京市',
        district: '鼓楼区',
        street: '鼓楼街道',
        address: '南京市鼓楼区鼓楼街道',
        distance: '3.2km'
      },
      liked: true,
      popularity: {
        views: 8923,
        favorites: 156,
        likes: 234,
        shares: 45,
        favoriteRate: '18%',
        goodRate: '98%',
        trend: 'up'
      },
      images: [
        { url: '/static/images/home/goods/2.png', type: 'main' },
        { url: '/static/images/home/goods/2_1.png', type: 'detail' },
        { url: '/static/images/home/goods/2_2.png', type: 'scene' },
        { url: '/static/images/home/goods/2_3.png', type: 'detail' }
      ],
      attributes: [
        { key: '成色', value: '全新' },
        { key: '颜色', value: '白色' },
        { key: '版本', value: '带屏遥控器版' },
        { key: '重量', value: '0.249kg' },
        { key: '尺寸', value: '132×81×58mm' },
        { key: '平台佣金比例', value: '5%' },
        { key: '寄卖周期', value: '30天' },
        { key: '平台质检状态', value: '已质检' },
        { key: '卖家发货截止时间', value: '2025-11-15' }
      ],
      services: ['7天无理由', '一年质保', '顺丰包邮', '飞行保险'],
      promotions: [
        { type: '赠品', title: '备用桨叶套装', value: '价值￥199' },
        { type: '分期', title: '花呗分期', detail: '￥198元/月' }
      ],
      seller: {
        id: 'seller102',
        name: '大疆官方旗舰店',
        avatar: '/static/images/avatar/3.jpg',
        description: '大疆官方旗舰店，专注大疆产品，提供最新、最全的大疆产品信息，服务客户10年以上。',
        tag: '品牌旗舰店',
        rating: 4.8,
        followed: true,
        auth: { realName: true, phone: true },
        status: 'online',
        stats: { goodsCount: 89, transactionCount: 3200, replyRate: '96%' },
        recommendedGoods: [
          { id: '1003', name: '大疆DJI Mini 2 Pro 无人机 专业航拍器', image: '/static/images/home/goods/2.png', price: 5699 },
          { id: '1004', name: '大疆DJI Mini 3 Pro 无人机 专业航拍器', image: '/static/images/home/goods/3.png', price: 6499 }
        ]
      },
      comments: { total: 892, goodRate: '98%', tags: ['画质清晰', '续航久', '避障灵敏'] }
    }
  ],

  // 商品详情数据
  goodsDetail: {
    '1001': {
      id: '1001',
      type: '自由交易',
      category: { first: '数码产品', second: '手机', id: 101 },
      title: 'iPhone X 苹果手机 全网通',
      subtitle: '64G 深空黑色 99新',
      description: 'Apple iPhone X 苹果手机，64G 深空黑色 99新，全网通，支持5G。',
      price: {
        current: 2999,
        original: 3699,
        drop: 700,
        cheaperThanSimilar: 300
      },
      status: "onSale",
      image: '/static/images/home/goods/1.png',
      location: {
        city: '北京市',
        district: '朝阳区',
        street: '望京街道',
        address: '北京市朝阳区望京SOHO',
        distance: '2.5km'
      },
      liked: true,
      popularity: {
        views: 15678,
        favorites: 234,
        likes: 567,
        shares: 89,
        favoriteRate: '15%',
        goodRate: '99%',
        trend: 'up'
      },
      images: [
        { url: '/static/images/home/goods/1.png', type: 'main' },
        { url: '/static/images/home/goods/2.png', type: 'detail' },
        { url: '/static/images/home/goods/3.png', type: 'detail' },
        { url: '/static/images/home/goods/4.png', type: 'defect' }
      ],
      attributes: [
        { key: '成色', value: '99新' },
        { key: '颜色', value: '深空黑色' },
        { key: '存储', value: '64G' },
        { key: '版本', value: '国行三网通' },
        { key: '重量', value: '0.17kg' },
        { key: '尺寸', value: '143.6×70.9×7.7mm' },
        { key: '电池健康', value: '85%' },
        { key: '购买日期', value: '2022-03-15' },
        { key: '保修截止', value: '2023-03-15' },
        { key: '维修记录', value: '无拆修' },
        { key: '验机报告', value: '已验机' },
        { key: '配件清单', value: '原装充电器、数据线、包装盒' },
        { key: '卖家描述', value: '自用手机，保养很好，无任何问题，因换新机出售。' }
      ],
      services: ['7天无理由', '180天质保', '顺丰包邮', '半年电池换新'],
      promotions: [
        { type: '赠品', title: '品胜充电器套装', value: '价值￥99' },
        { type: '分期', title: '花呗分期', detail: '￥318元/月' }
      ],
      seller: {
        id: 'seller101',
        name: '苹果官方旗舰店',
        avatar: '/static/images/avatar/1.jpg',
        description: '苹果官方旗舰店，专注苹果产品，提供最新、最全的苹果产品信息，服务客户10年以上。',
        tag: '官方认证',
        rating: 4.9,
        followed: true,
        auth: { realName: true, phone: true },
        status: 'online',
        stats: { goodsCount: 156, transactionCount: 2345, replyRate: '98%' },
        recommendedGoods: [
          { id: '1001', title: 'iPhone X 苹果手机 全网通', price: 2999, image: '/static/images/home/goods/1.png' },
          { id: '1002', title: 'Canon EOS M50 Mark II微单相机', price: 1999, image: '/static/images/home/goods/2.png' }
        ]
      },
      comments: { total: 1234, goodRate: '99%', tags: ['成色新', '电池耐用', '服务好'] }
    },
    'new_1763043230284': {
      id: 'new_1763043230284',
      type: '自由交易',
      category: { first: '数码产品', second: '其他数码', id: 2 },
      title: '二手商品',
      subtitle: '9成新 2021-09-10购买',
      description: '56436543654365',
      price: {
        current: 56,
        original: 555,
        drop: 500,
        cheaperThanSimilar: 0
      },
      status: 'onSale',
      image: '/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png',
      images: ['/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png'],
      tradeType: '上门自提',
      tradeDetails: '4325436565436543654365365765765',
      location: {
        city: '北京市',
        district: '海淀区',
        street: '中关村街道',
        address: '北京市海淀区中关村',
        distance: '3.8km'
      },
      liked: false,
      popularity: {
        views: 123,
        favorites: 5,
        likes: 8,
        shares: 2,
        favoriteRate: '4%',
        goodRate: '100%',
        trend: 'up'
      },
      images: [
        { url: '/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png', type: 'main' }
      ],
      attributes: [
        { key: '商品状态', value: '9成新' },
        { key: '购买时间', value: '2021-09-10' },
        { key: '保修情况', value: '不保修' },
        { key: '配件情况', value: '654365' }
      ],
      services: ['正品保障', '7天无理由退货'],
      promotions: [],
      seller: {
        id: 'seller103',
        name: '普通卖家',
        avatar: '/static/images/avatar/default.jpg',
        description: '个人卖家，专注二手商品交易',
        tag: '个人卖家',
        rating: 4.7,
        followed: false,
        auth: { realName: true, phone: true },
        status: 'offline',
        stats: { goodsCount: 12, transactionCount: 45, replyRate: '95%' },
        recommendedGoods: [
          { id: 'new_1763043230284', title: '二手商品', price: 56, image: '/api/upload/images/1763042926276-d8772f50-652c-4d11-b6ad-999c1c361e09.png' }
        ]
      },
      comments: { total: 0, goodRate: '0%', tags: [] }
    }
  },

  // 常见问题数据
  commonQuestions: {
    '1001': [
      { id: 1, question: '这个手机是正品吗？', answer: '是的，我们保证所有商品都是正品，支持官方验机。' },
      { id: 2, question: '支持验机吗？', answer: '支持，我们提供专业的验机服务，确保商品质量。' },
      { id: 3, question: '有发票吗？', answer: '可以提供电子发票，购买后联系客服获取。' },
      { id: 4, question: '保修多久？', answer: '提供180天质保服务，具体保修条款详见商品详情。' },
      { id: 5, question: '可以分期付款吗？', answer: '支持花呗、京东白条、信用卡分期等多种支付方式。' }
    ]
  },

  // 商品问答数据
  goodsQuestions: {
    '1001': [
      {
        id: 1,
        username: '买家A',
        avatar: '/static/images/avatar/5.jpg',
        question: '这个手机支持5G吗？',
        answer: '是的，支持5G网络，网速很快。',
        answerUser: '卖家',
        answerAvatar: '/static/images/avatar/1.jpg',
        time: '2小时前',
        answerTime: '2小时前'
      }
    ]
  },

  // 商品评论数据
  goodsComments: {
    '1001': [
      {
        id: 1,
        username: '转转用户',
        avatar: '/static/images/avatar/1.jpg',
        content: '这个手机非常不错，屏幕质量很好，价格也相对来说便宜。',
        spec: 'iPhoneX苹果银色256G其他版本',
        rating: 5
      }
    ]
  },

  //根据不同分类获取属性
  categorySpecs: {
    // 根据分类类型生成对应的规格参数
    'digital': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '内存/存储', value: '', placeholder: '请填写内存或存储容量' },
      { label: '颜色', value: '', placeholder: '请填写颜色' },
      { label: '功能', value: '', placeholder: '请填写主要功能' }
    ],
    'culture': [
      { label: '作者/出版社', value: '', placeholder: '请填写作者或出版社' },
      { label: '出版时间', value: '', placeholder: '请填写出版时间' },
      { label: '页数/时长', value: '', placeholder: '请填写页数或时长' },
      { label: 'ISBN/编号', value: '', placeholder: '请填写ISBN或编号' }
    ],
    'clothing': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '尺码', value: '', placeholder: '请填写尺码' },
      { label: '材质', value: '', placeholder: '请填写材质' },
      { label: '颜色', value: '', placeholder: '请填写颜色' },
      { label: '季节', value: '', placeholder: '请填写适用季节' }
    ],
    'vehicle': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '排量/功率', value: '', placeholder: '请填写排量或功率' },
      { label: '颜色', value: '', placeholder: '请填写颜色' },
      { label: '里程/使用时间', value: '', placeholder: '请填写里程或使用时间' }
    ],
    'baby': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '适用年龄', value: '', placeholder: '请填写适用年龄' },
      { label: '材质', value: '', placeholder: '请填写材质' },
      { label: '颜色', value: '', placeholder: '请填写颜色' },
      { label: '安全认证', value: '', placeholder: '请填写安全认证' }
    ],
    'appliance': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '功率', value: '', placeholder: '请填写功率' },
      { label: '容量', value: '', placeholder: '请填写容量' },
      { label: '功能', value: '', placeholder: '请填写主要功能' }
    ],
    'furniture': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '材质', value: '', placeholder: '请填写材质' },
      { label: '尺寸', value: '', placeholder: '请填写尺寸' },
      { label: '颜色', value: '', placeholder: '请填写颜色' },
      { label: '风格', value: '', placeholder: '请填写风格' }
    ],
    'sports': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '尺寸', value: '', placeholder: '请填写尺寸' },
      { label: '材质', value: '', placeholder: '请填写材质' },
      { label: '适用场景', value: '', placeholder: '请填写适用场景' }
    ],
    'beauty': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '容量', value: '', placeholder: '请填写容量' },
      { label: '保质期', value: '', placeholder: '请填写保质期' },
      { label: '功效', value: '', placeholder: '请填写主要功效' }
    ],
    'computer': [
      { label: '品牌', value: '', placeholder: '请填写品牌' },
      { label: '型号', value: '', placeholder: '请填写型号' },
      { label: '配置', value: '', placeholder: '请填写配置信息' },
      { label: '内存/存储', value: '', placeholder: '请填写内存或存储容量' },
      { label: '屏幕尺寸', value: '', placeholder: '请填写屏幕尺寸' }
    ]
  }
};

// 获取商品列表
router.post('/goodsList', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, categoryId, keyword } = req.body;
    
    // 构建查询条件
    const where = {};
    if (categoryId) {
      where.category_id = categoryId;
    }
    if (keyword) {
      where.title = {
        [Sequelize.Op.like]: `%${keyword}%`
      };
    }
    
    // 查询商品列表，包含关联的属性和卖家信息
    const { count, rows } = await Goods.findAndCountAll({
      where,
      include: [
        {
          model: GoodsAttributes,
          as: 'attributes'
        },
        {
          model: Seller,
          as: 'seller'
        }
      ],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      order: [['created_at', 'DESC']] // 按创建时间倒序
    });
    
    // 转换数据格式以匹配前端期望的结构
    const formattedGoods = rows.map(goods => ({
      id: goods.id,
      type: goods.trade_type === 'direct' ? '自由交易' : '平台托管',
      category: {
        // 这里需要根据实际数据库结构调整
        first: goods.category_name || '未知分类',
        second: goods.subcategory_name || '',
        id: goods.category_id
      },
      title: goods.title,
      subtitle: goods.subtitle || '',
      description: goods.description,
      price: {
        current: goods.current_price,
        original: goods.original_price || goods.current_price,
        drop: goods.original_price ? goods.original_price - goods.current_price : 0,
        cheaperThanSimilar: 0 // 可以根据业务逻辑计算
      },
      status: goods.status,
      image: goods.image,
      location: {
        city: goods.location?.city || '未知城市',
        district: goods.location?.district || '',
        street: goods.location?.street || '',
        address: goods.location?.address || '',
        distance: '0km' // 可以根据用户位置计算
      },
      liked: false, // 默认未收藏
      popularity: {
        views: goods.view_count || 0,
        favorites: goods.favorite_count || 0,
        likes: goods.like_count || 0,
        shares: goods.share_count || 0,
        favoriteRate: '0%',
        goodRate: '0%',
        trend: 'up'
      },
      images: goods.images ? JSON.parse(goods.images) : [],
      attributes: goods.attributes ? goods.attributes.map(attr => ({
        key: attr.attr_key,
        value: attr.attr_value
      })) : [],
      services: goods.services ? JSON.parse(goods.services) : [],
      promotions: goods.promotions ? JSON.parse(goods.promotions) : [],
      seller: goods.seller ? {
        id: goods.seller.id,
        name: goods.seller.name,
        avatar: goods.seller.avatar || '/static/images/avatar/default.jpg',
        auth: {
          realName: goods.seller.real_name || '',
          phone: goods.seller.phone || '',
        },
        rating: goods.seller.rating || 0,
        status: goods.seller.status || 'offline',
        stats: {
          goodsCount: goods.seller.goods_count || 0,
          transactionCount: goods.seller.transaction_count || 0,
          replyRate: '0%'
        }
      } : null,
      comments: {
        total: goods.comment_count || 0,
        goodRate: '0%',
        tags: []
      }
    }));

    res.json({
      code: 200,
      message: '成功',
      data: {
        list: formattedGoods,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(count / pageSize)
      }
    });
  } catch (error) {
    console.error('获取商品列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 获取商品详情
router.post('/goodsDetail', async (req, res) => {
  try {
    const { id } = req.body;
    
    // 使用ORM查询商品详情，包含关联的属性数据
    const goodsDetail = await Goods.findOne({
      where: { id },
      include: [
        {
          model: GoodsAttributes,
          as: 'attributes'
        },
        {
          model: Seller,
          as: 'seller'
        }
      ]
    });
console.log('卖家信息', goodsDetail.seller)
    if (!goodsDetail) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    // 转换数据格式
    const responseData = {
      id: goodsDetail.id,
      type: goodsDetail.trade_type === 'direct' ? '自由交易' : '平台托管',
      title: goodsDetail.title,
      tradeType: goodsDetail.trade_type,
      tradeDetails: goodsDetail.trade_details || '',
      description: goodsDetail.description,
      price: {
        current: goodsDetail.current_price,
        original: goodsDetail.original_price || goodsDetail.current_price,
        drop: goodsDetail.original_price ? goodsDetail.original_price - goodsDetail.current_price : 0,
        cheaperThanSimilar: 0 // 可以根据业务逻辑计算
      },
      location: {
        city: goodsDetail.location?.city || '未知城市',
        district: goodsDetail.location?.district || '',
        street: goodsDetail.location?.street || '',
        address: goodsDetail.location?.address || '',
        distance: '0km' // 可以根据用户位置计算
      },
      liked: false,
      popularity: {
        views: goodsDetail.view_count || 0,
        favorites: goodsDetail.favorite_count || 0,
        likes: goodsDetail.like_count || 0,
        shares: goodsDetail.share_count || 0,
        favoriteRate: '0%',
        goodRate: '0%',
        trend: 'up'
      },
      status: goodsDetail.status,
      image: goodsDetail.image,
      // 转换属性格式
      attributes: goodsDetail.attributes ? goodsDetail.attributes.map(attr => ({
        key: attr.attr_key,
        value: attr.attr_value
      })) : [],
      // 添加卖家信息
      seller: goodsDetail.seller ? {
        id: goodsDetail.seller.id,
        name: goodsDetail.seller.name,
        description: goodsDetail.seller.description || '',
        avatar: goodsDetail.seller.avatar || '/static/images/avatar/default.jpg',
        rating: goodsDetail.seller.rating || 0,
        realNameAuth: goodsDetail.seller.real_name_auth || 0,
        phoneAuth: goodsDetail.seller.phone_auth || 0,
        status: goodsDetail.seller.status || 'offline',
        goodsCount: goodsDetail.seller.goods_count || 0,
        transactionCount: goodsDetail.seller.transaction_count || 0,
        replyRate: goodsDetail.seller.reply_rate || '0%',
        recommendedGoods: [{
          id: 1,
          image: '/static/images/goods/1.jpg',
          price: 99.99,
          title: '商品名称',
          description: '商品描述'
        }]
      } : null,
      comments: {
        total: goodsDetail.comments?.count || 0,
        goodRate: '0%',
        tags: []
      }
    };

    res.json({
      code: 200,
      message: '成功',
      data: responseData
    });
  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 获取常见问题
router.post('/commonQuestions', (req, res) => {
  try {
    const { goods_id } = req.body;
    const questions = mockGoodsData.commonQuestions[goods_id] || [];

    res.json({
      code: 200,
      message: '成功',
      data: questions
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 获取商品问答
router.post('/goodsQuestions', (req, res) => {
  try {
    const { goods_id } = req.body;
    const questions = mockGoodsData.goodsQuestions[goods_id] || [];

    res.json({
      code: 200,
      message: '成功',
      data: questions
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 获取商品评论
router.post('/comments', (req, res) => {
  try {
    const { goods_id } = req.body;
    const comments = mockGoodsData.goodsComments[goods_id] || [];

    res.json({
      code: 200,
      message: '成功',
      data: comments
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 导入ORM模型
const { Goods, GoodsAttributes, Seller } = require('../models');
const Sequelize = require('sequelize');

// 提交商品
router.post('/submit', async (req, res) => {
  try {
    const goodsData = req.body;
    
    // 生成商品ID
    const goodsId = 'goods_' + Date.now();
    // 使用默认卖家ID（实际应用中应从用户登录信息获取）
    const sellerId = 'seller_001';
    
    // 使用ORM插入商品基本信息
    const goods = await Goods.create({
      id: goodsId,
      seller_id: sellerId,
      type: 'secondhand', // 商品类型
      trade_type: goodsData.tradeType,
      trade_details: goodsData.tradeDetails,
      title: goodsData.description.substring(0, 20) + '...', // 截取部分描述作为标题
      description: goodsData.description,
      category_id: goodsData.categoryId,
      current_price: goodsData.price,
      original_price: goodsData.originalPrice,
      image: goodsData.images[0],
      status: 'onSale' // 商品状态
    });
    
    // 使用ORM插入商品属性
    const attributes = [];
    if (goodsData.specs && typeof goodsData.specs === 'object') {
      const specsEntries = Object.entries(goodsData.specs);
      for (const [key, value] of specsEntries) {
        await GoodsAttributes.create({
          goods_id: goodsId,
          attr_key: key,
          attr_value: value
        });
        attributes.push({ name: key, value: value });
      }
    }
    
    // 返回成功响应
    res.json({
      code: 200,
      message: '商品发布成功',
      data: {
        id: goodsId,
        goodsId: goodsId,
        ...goodsData,
        attributes: attributes
      }
    });
    
  } catch (error) {
    console.error('提交商品失败:', error);
    res.status(500).json({
      status: 'error',
      message: '商品发布失败',
      error: error.message
    });
  }
});
// 提交商品
router.post('/generateCategorySpecs', (req, res) => {
  try {
    const { type } = req.body;
    if (!type) {
      type = 'default';
    }
    let data = mockGoodsData.categorySpecs[type];
    if (!data) {
      data = [
        { label: '品牌', value: '', placeholder: '请填写品牌' },
        { label: '型号', value: '', placeholder: '请填写型号' },
        { label: '详细参数', value: '', placeholder: '请填写详细参数' }
      ]
    }

    // 模拟提交成功
    res.json({
      code: 200,
      message: '商品提交成功',
      data: data
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});
module.exports = router;